﻿//-----------------------------------------------------------------------
// <copyright file="FormControls.cs" author="Lennart">
//     License: MIT
// </copyright>
//-----------------------------------------------------------------------
namespace UtilityMethods {
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Windows.Forms;

    /// <summary>
    /// Provides functions to use with various WinForms controls.
    /// </summary>
    public static class FormControls {
        /// <summary>
        /// Auto-sizes the columns in the DataGridView.
        /// </summary>
        /// <param name="toFit">The DataGridView in which the columns should be adjusted.</param>
        public static void FitColumns(DataGridView toFit) {
            for (int i = 0; i < toFit.Columns.Count; i++) {
                toFit.Columns[i].AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells;
            }
        }

        /// <summary>
        /// Writes the DataGridView to a CSV file.
        /// </summary>
        /// <param name="dgvToSave">The DataGridView to dump.</param>
        public static void WriteDGVtoCSV(DataGridView dgvToSave) {
            var data = new StreamWriter(Path.GetTempPath() + @"data.csv");
            foreach (DataGridViewRow row in dgvToSave.Rows) {
                foreach (DataGridViewCell rowData in row.Cells) {
                    if (rowData != null) {
                        data.Write(rowData.Value.ToString() + ",");
                    }

                    Debug.WriteLine(rowData.Value.ToString() + ",");
                }

                data.Write(Environment.NewLine);
            }

            data.Close();
            data.Dispose();
        }

        /// <summary>
        /// Populates the DataGridView from the CSV file.
        /// </summary>
        /// <param name="dgvToLoad">The DataGridView that should be loaded.</param>
        public static void LoadDGVfromCSV(DataGridView dgvToLoad) {
            if (File.Exists(Path.GetTempPath() + @"data.csv")) {
                using (StreamReader sr = new StreamReader(Path.GetTempPath() + @"data.csv")) {
                    string row;
                    int rowsLoaded = 0;
                    while (sr.Peek() != -1) {
                        row = sr.ReadLine();
                        string[] cell = row.Split(new char[] { ',' });
                        dgvToLoad.Rows.Insert(rowsLoaded, cell[0], ShortcutInfo.GetIcon(cell[3] + "\\" + cell[2]), cell[2], cell[3], cell[4]);
                        rowsLoaded++;
                    }
                }
            }
        }
    }
}
